<template>
  <div class="unit-info">
    <el-form
      :model="unitForm"
      ref="unitFormRef"
      :rules="queryRules"
      label-width="130px"
    >
      <!-- <div class="search-button">
      <el-button type="primary" @click="handleAddSave"
        ><img src="@/assets/images/Submit.png" alt="" /> 提交</el-button
      >
      <el-button @click="handleBack" color="#efbf00"
        ><img src="@/assets/images/back.png" alt="" />
        <span style="color: #ffffff">返回</span>
      </el-button>
    </div> -->
      <div class="middle-top">
        <div class="middle-title">
          <img src="@/assets/images/title-icon.png" alt="" />
          人员信息
        </div>
      </div>

      <el-row>
        <el-col :span="12">
          <el-form-item
            label="姓名："
            prop="screeningPersonnelName"
            label-width="130"
          >
            <el-input
              v-model="unitForm.screeningPersonnelName"
              placeholder="请输入姓名"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="现居住地址："
            prop="currentResidentialAddress"
            label-width="130"
          >
            <el-input
              v-model="unitForm.currentResidentialAddress"
              placeholder="请输入现居住地址"
              clearable
              maxlength="30"
              class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工作单位：" prop="workUnit" label-width="130">
            <el-input
              v-model="unitForm.workUnit"
              placeholder="请输入工作单位"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="工作职业："
            prop="jobOccupation"
            label-width="130"
          >
            <el-input
              v-model="unitForm.jobOccupation"
              placeholder="请输入工作职业"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="身份证号码："
            prop="identityCard"
            label-width="130"
          >
            <el-input
              v-model="unitForm.identityCard"
              placeholder="请输入身份证号码"
              clearable
              disabled
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话：" prop="phone" label-width="130">
            <el-input
              v-model="unitForm.phone"
              placeholder="请输入联系电话"
              clearable
              maxlength="20"
              class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="辖区派出所：" prop="policeId" label-width="130">
            <el-select
              v-model="unitForm.policeId"
              placeholder="请选择辖区派出所"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="dict in policeOptions"
                :key="dict.deptId"
                :label="dict.deptName"
                :value="dict.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="display: flex">
          <el-form-item
            label="户籍地派出所："
            prop="whetherHarbin"
            label-width="130"
            style="width: 300px;"
          >
            <el-select
              v-model="unitForm.whetherHarbin"
              placeholder="请选择是否哈尔滨"
              clearable
              style="width: 100%"
              @change="handleWhetherChange"
            >
              <el-option
                v-for="dict in whetherHarbinOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item
              v-if="unitForm.whetherHarbin === 1"
              label=""
              style="width: 400px;"
              prop="localPoliceStationId"
              label-width="10"
          >
            <el-select
                v-model="unitForm.localPoliceStationId"
                placeholder="请选择户籍地派出所"
                clearable
                style="width: 100%"
            >
              <!-- :disabled="unitForm.whetherHarbin === ''" -->
              <el-option
                  v-for="dict in policeOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
              />
            </el-select>
          </el-form-item>

          <el-form-item
              label=""
              prop="localPoliceStation"
              label-width="10"
              style="width: 400px;"
              v-else
          >
            <el-input
                v-model="unitForm.localPoliceStation"
                placeholder="请输入户籍地派出所"
                clearable
                maxlength="20"
                class="search-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="middle-top">
        <div class="middle-title">
          <img src="@/assets/images/title-icon.png" alt="" />
          无人机
        </div>
        <el-button type="primary" @click="addTable">添加</el-button>
      </div>
      <div class="fly-title">
          当前持有 {{ unitForm.personneUavInfoRespVos.length }} 架无人机
      </div>
      <!-- 表格数据 -->
      <el-table
        :data="unitForm.personneUavInfoRespVos"
        border
        height="30vh"
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column
          label="无人机品牌"
          prop="droneBrand"
          :show-overflow-tooltip="true"
        >
          <template #header>
            <span class="verify-icon">无人机品牌</span>
          </template>
          <template #default="{ row, $index }">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :prop="'personneUavInfoRespVos.' + $index + '.droneBrand'"
              :rules="rules.droneBrand"
            >
              <el-input
              maxlength="10"
                v-model="row.droneBrand"
                clearable
                size="mini"
                placeholder="请填写"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="无人机型号"
          prop="uavModel"
          :show-overflow-tooltip="true"
        >
        <template #header>
            <span class="verify-icon">无人机型号</span>
          </template>
          <template #default="{ row, $index }">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :prop="'personneUavInfoRespVos.' + $index + '.uavModel'"
              :rules="rules.uavModel"
            >
              <el-input maxlength="10"
                v-model="row.uavModel"
                clearable
                size="mini"
                placeholder="请填写"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column
          label="无人机识别码"
          prop="droneIdentificationCode"
          :show-overflow-tooltip="true"
        >
        <template #header>
            <span class="verify-icon">无人机识别码</span>
          </template>
          <template #default="{ row, $index }">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :prop="
                'personneUavInfoRespVos.' + $index + '.droneIdentificationCode'
              "
              :rules="rules.droneIdentificationCode"
            >
              <el-input maxlength="30"
                v-model="row.droneIdentificationCode"
                @input="inputNoZW($index)"
                clearable
                size="mini"
                placeholder="请填写"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="本人/单位使用"
          prop="useType"
          :show-overflow-tooltip="true"
          width="200px"
        >
        <template #header>
            <span class="verify-icon">本人/单位使用</span>
          </template>
          <template #default="{ row, $index }">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :prop="'personneUavInfoRespVos.' + $index + '.useType'"
              :rules="rules.useType"
            >
              <el-select
                v-model="row.useType"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in useType"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="用途"
          prop="purpose"
          :show-overflow-tooltip="true"
          width="180"
        >
        <template #header>
            <span class="verify-icon">用途</span>
          </template>
          <template #default="{ row, $index }">
            <el-form-item
              label=""
              label-width="0"
              style="margin-bottom: 0"
              :prop="'personneUavInfoRespVos.' + $index + '.purpose'"
              :rules="rules.purpose"
            >
              <el-input maxlength="30"
                v-model="row.purpose"
                clearable
                size="mini"
                placeholder="请填写"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          :show-overflow-tooltip="true"
          width="180"
        >
          <template #default="{ row }">
            <el-form-item label="" label-width="0" style="margin-bottom: 0">
              <el-input
                maxlength="30"
                v-model="row.remark"
                clearable
                size="mini"
                placeholder="请填写"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="60px"
        >
          <template #default="{ $index }">
            <div class="table-operate">
              <el-icon
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleDelete($index)"
              >
                <Delete />
              </el-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Selectmap from "./selectmap";
import {
  addinstitution,
  editPeopleApi,
  selectDeptListByUser,
  getPepleInfoApi,
  getPoliceSonListApi,
} from "@/api/erp/unit";
import { getAreaList } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";

const props = defineProps({
  // 操作类型
  showdialog: {
    type: Boolean,
    default: false,
  },
  //行业主管下拉
  supervisorList: {
    type: Array,
    default: [],
  },
  //单位类型数据
  unittypeList: {
    type: Array,
    default: [],
  },
  //单位级别下拉
  unitlevelList: {
    type: Array,
    default: [],
  },
});

const userStore = useUserStore();

const emit = defineEmits(["refreshList"]);

let pagestatus = ref(null);

let options = ref([]);

const whetherHarbinOptions = ref([
  {
    dictValue: 1,
    dictLabel: "是",
  },
  {
    dictValue: 0,
    dictLabel: "否",
  },
]);

const policeOptions = ref([]);

const areaprops = {
  lazy: true,
  checkStrictly: true,
  lazyLoad(node, resolve) {
    const { level } = node;
    let datas = [];
    setTimeout(() => {
      let code = 1;
      if (level != 0) {
        code = node.data.value;
      }
      getAreaList({ pid: code }).then((response) => {
        if (response.data && response.data.length) {
          datas = response.data.map((item, i) => ({
            value: item.value,
            label: item.label,
            leaf: level >= 3,
            // disabled: level < 3, // 这里可以设置为 true 来禁用这个选项
          }));
        } else {
          datas = [];
        }
        resolve(datas);
      });
    }, 200);
  },
};
//省市区校验规则
const provinceValidate = (rule, value, callback) => {
  // const { province, city, area } = projectForm.value;
  // if (!province || !city || !area) {
  //   callback(new Error("请选择省市区"));
  // } else {
  //   callback();
  // }
  const { region } = unitForm.value;
  console.log("region.length", region.length);
  if (region.length == 0) {
    console.log("zhixn");
    callback(new Error("请选择省市区街道"));
  } else if (region.length < 4) {
    console.log(2);
    callback(new Error("请选择到街道"));
  } else {
    callback();
  }
};

const inputNoZW = (index) => {
  unitForm.value.personneUavInfoRespVos[index].droneIdentificationCode = unitForm.value.personneUavInfoRespVos[index].droneIdentificationCode.replace(/[\u4e00-\u9fa5]/g, '');
}

const useType = ref([
  {
    dictLabel: "本人使用",
    dictValue: 0,
  },
  {
    dictLabel: "单位使用",
    dictValue: 1,
  },
]);

const unitForm = ref({
  region: [],
  personneUavInfoRespVos: [],
  currentResidentialAddress: "",
  policeId: null,
  workUnit: "",
  localPoliceStationId: null,
  screeningPersonnelName: "",
  jobOccupation: "",
  whetherHarbin: null,
  identityCard: "",
  controlType: null,
  phone: "",
  personnelType: null,
  screeningPersonnelId: null,
  policyAdvocacy: null,
  localPoliceStation: "",
});

const rules = ref({
  droneBrand: [
    { required: true, message: "请输入无人机品牌", trigger: "blur" },
  ],
  uavModel: [{ required: true, message: "请输入无人机型号", trigger: "blur" }],
  purpose: [{ required: true, message: "请输入用途", trigger: "blur" }],
  droneIdentificationCode: [
    { required: true, message: "请输入无人机识别码", trigger: "blur" },
  ],
  useType: [
    { required: true, message: "请选择本人/单位使用", trigger: "change" },
  ],
});

const queryRules = ref({
  screeningPersonnelName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
  ],
  currentResidentialAddress: [
    { required: true, message: "请输入现居住地址", trigger: "blur" },
  ],
  workUnit: [{ required: true, message: "请输入工作单位", trigger: "blur" }],
  jobOccupation: [
    { required: true, message: "请输入工作职业", trigger: "blur" },
  ],
  identityCard: [
    { required: true, message: "请输入身份证号码", trigger: "blur" },
  ],
  phone: [{ required: true, message: "请输入联系电话", trigger: "blur" },

  {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的联系电话",
        trigger: "blur",
      }

  ],
  policeId: [
    { required: true, message: "请选择辖区派出所", trigger: "change" },
  ],
  whetherHarbin: [
    { required: true, message: "请选择是否哈尔滨", trigger: "change" },
  ],
  localPoliceStationId: [
    { required: true, message: "请选择户籍地派出所", trigger: "change" },
  ],
  localPoliceStation: [
    { required: true, message: "请选择户籍地派出所", trigger: "change" },
  ],
});

//详细地址地图选择弹窗显隐
let isshowmap = ref(false);

//所属派出所
const policeList = ref([]);

/**
 * @description: 地图详细地址
 */
const selectaddress = () => {
  isshowmap.value = true;
};
//表格删除
const handleDelete = (tabIndex) => {
  ElMessageBox.confirm("此操作将删除该无人机，是否继续？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
    type: "warning",
  })
    .then(async () => {
      unitForm.value.personneUavInfoRespVos.splice(tabIndex, 1);
    })
    .catch(() => {});
};

/**
 * @description: 联级处理省市区操作
 * @param {String} type 类型
 */
const handlerregion = (value) => {
  if (value) {
    switch (value.length) {
      case 1:
        unitForm.value.provinceId = value[0];
        break;
      case 2:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        break;
      case 3:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        unitForm.value.zoneId = value[2];
        break;
      case 4:
        unitForm.value.provinceId = value[0];
        unitForm.value.cityId = value[1];
        unitForm.value.zoneId = value[2];
        unitForm.value.streetId = value[3];
        break;
      default:
        break;
    }
  } else {
    unitForm.value.region = [];
    unitForm.value.provinceId = null;
    unitForm.value.cityId = null;
    unitForm.value.zoneId = null;
    unitForm.value.streetId = null;
  }
};

/**
 * @description: 提交
 * @param {Object} customerFormRef 客户表单引用
 */
const unitFormRef = ref(null);
const handleAddSave = async () => {
  await unitFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          console.log("unitForm.value", unitForm.value);
          let Fun;
          if (pagestatus.value == "edit") {
            Fun = editPeopleApi;
          } else {
            Fun = addinstitution;
          }
          Fun(unitForm.value).then((res) => {
            if (res.code === 200) {
              emit("update:showUnitadd", false);
              emit("refreshList");
              ElMessage.success(res.msg);
              unitForm.value = {
                region: [],
              };
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  });
};

const handleWhetherChange = (value) => {
  if (value === 1) {
    unitForm.value.localPoliceStation = "";
  } else if (value === 0) {
    unitForm.value.localPoliceStationId = "";
  } else {
    unitForm.value.localPoliceStation = "";
    unitForm.value.localPoliceStationId = "";
  }
};

// 表格新增
const addTable = () => {
  let info = {
    droneBrand: "",
    uavModel: "",
    purpose: "",
    droneBrand: "",
    droneIdentificationCode: "",
    useType: null,
  };
  unitForm.value.personneUavInfoRespVos.push(info);
};

//处理编辑
const handleEdit = async (row) => {
  console.log("row", row);
  const res = await getPepleInfoApi(row.screeningPersonnelId);
  console.log("详情信息》》》》》》》》");
  console.log(res);
  row.personneUavInfoRespVos = [];
  unitForm.value = {
    ...res.data,
    personneUavInfoRespVos: res.data.personneUavInfoRespVos || [],
  };
  pagestatus.value = "edit";
};

// 处理提交
const handleSubmit = async () => {
  console.log("提交》》》》》》》》》》");
  console.log(unitForm.value);
  await unitFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          console.log("unitForm.value", unitForm.value);
          editPeopleApi(unitForm.value).then((res) => {
            if (res.code === 200) {
              emit("update:showUnitadd", false);
              emit("refreshList");
              ElMessage.success(res.msg);
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  });
};

/**
 * @description:  获取派出所
 * @param {Number} id
 */
const getpolicestation = () => {
  getPoliceSonListApi().then((res) => {
    console.log("获取派出所");
    console.log(res);
    policeOptions.value = res;
  });
};

onMounted(() => {
  getpolicestation();
});

defineExpose({
  handleEdit,
  handleSubmit,
});
</script>

<style scoped lang="scss">
.unit-info {
  // margin-top: 20px;
  padding: 0 20px;
}
.fly-title {
  background-color: #FFF0DD;
  height: 40px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color:#EE574A;
}
.verify-icon::before {
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
.middle-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  .middle-title {
    font-size: 16px;
  }
}
:deep(.el-input-group__append) {
  padding: 0px 2px !important;
}
.search-button {
}
</style>
